<!--三包预警参数管理 经销商端-->
<template>
  <div>
    <TopFilter ref="topfilter" :list="topFilterList" :cols="4" labelWidth="100" :collapse="true" @filterChange="changeHandle" @onCollapse="collapseHandle"></TopFilter>
    <FilterTable
      :onSyncTableData="tableChangeFun"
      :isExportExcel="false"
      exportFileName="三包预警参数管理.xlsx"
      :onCalcExportData="handleExportFun"
      :onCellChange="onCellChange"
      :cellstyles="cellstyles"
      ref="table"
      :columns="columns"
      :fetchapi="fetchApi"
      :params="fetchParams"
      datakey="records"
      :isSelectColumn="false"
      :onColumnsChange="columns => (this.columns = columns)"
    >
      <template slot="controls" slot-scope="props">
        <multiuse-button type="primary" :click="exportHandle.bind(this)">导出</multiuse-button>
      </template>
    </FilterTable>

    <Drawer :visible.sync="visibleDetail" :title="dialogTitle" destroyOnClose :containerStyle="{ height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px' }">
      <detail :formData="formData" @close="closeHandler" :handleType="handleType" />
    </Drawer>
  </div>
</template>

<script>
import { dictionary } from '@/utils/dictMixin';
import detail from './detail';
import { isEmpty } from '@/utils/utils';
import { listParaRecord, updatePara, exportParaRecord } from '@/api/repair/threePacksOfManager/warningParameterManagementJingxsDuan';
import { arrayObjDeWeight } from '@/utils';
import { getAllUser } from '@/api/repair/batchEventManagement/activityDistribution';
import { dealerMixin } from '@/pages/repair/batchEventManagement/dealerMixin';

export default {
  name: 'addItem',
  mixins: [dictionary, dealerMixin],
  data() {
    this.BaseTable = null;
    this.conf = { add: '新增', edit: '编辑', show: '显示' };
    return {
      topFilterList: this.createTopFilterList(),
      visible: false,
      visibleDetail: false,
      fetchApi: listParaRecord,
      dialogTitle: '',
      fetchParams: { xhrAbort: false },
      columns: this.createTableColumns(),
      handleType: '',
      formData: {},
      cellstyles: [],
      tableData: []
    };
  },
  components: {
    detail
  },

  mounted() {
    this.BaseTable = this.$refs.table.$refs.pageTable;
    this.initSelect();
  },
  methods: {
    async exportHandle() {
      const [err, params] = await this.$refs.topfilter.GET_FORM_DATA();

      await this.downHandleFile(exportParaRecord, params, '三包预警参数管理');
    },

    async initSelect() {},
    dealerTranslate() {
      let userIds = [];
      this.tableData.forEach(item => {
        userIds.push(item.createdBy);
        userIds.push(item.updatedBy);
      });
      if (!userIds.length) return;
      let newUserIds = Array.from(new Set(userIds)); // 数组去重
      this.getNameByIds(this.columns, newUserIds.join(','), ['createdBy', 'updatedBy'], 'table');
    },
    tableChangeFun(dataList) {
      this.tableData = dataList;
      this.dealerTranslate();
      dataList.forEach((item, index) => {
        this.cellstyles.push({ row: item, dataIndex: 'red', styles: { backgroundColor: 'red' } });
        this.cellstyles.push({ row: item, dataIndex: 'orange', styles: { backgroundColor: 'orange' } });
        this.cellstyles.push({ row: item, dataIndex: 'yellow', styles: { backgroundColor: 'yellow' } });

        // item['createdBy']=Number(item['createdBy'])
        // item['updatedBy']=Number(item['updatedBy'])
      });

      console.log('tableChangeFun---', dataList);
    },

    /*配置数量发生改变的时候执行*/
    onCellChange(e, obj) {
      // this.BaseTable.DO_REFRESH(false)
    },
    // 导出处理函数
    handleExportFun(row) {
      row.status = row.status == '10041001' ? '锁定' : '解锁';
      row.type = this.createDictText(row.type, 1023);
    },

    async saveHandle(row, status) {
      let red = isEmpty(row['red']) ? '0' : row['red'];
      let yellow = isEmpty(row['yellow']) ? '0' : row['yellow'];
      let orange = isEmpty(row['orange']) ? '0' : row['orange'];

      let res = await updatePara({
        paraId: row['paraId'],
        red: red,
        yellow: yellow,
        orange: orange,
        status: status
      });
      if (res.resultCode == 200 && res.success == true) {
        this.fetchParams = { ...this.fetchParams };

        this.$notify.success({ title: '提示信息', message: '操作成功' });
      }
    },

    detailHandle(row) {
      this.formData = row;
      this.handleType = 'show';
      this.showHandler();
    },

    createTableColumns() {
      return [
        {
          title: '序号',
          dataIndex: 'index',
          width: 70,
          sorter: true,
          fixed: 'left',
          render: props => {
            return <span>{props.row.index + 1}</span>;
          }
        },
        {
          title: '操作',
          dataIndex: 'column-action',
          width: 120,
          render: props => {
            let status = props.row.status == '10041001' ? '10041002' : '10041001';
            let statusName = props.row.status == '10041001' ? '锁定' : '解锁';

            // <el-divider direction="vertical"/>
            // <multiuse-button type="text"
            //                  size="mini"
            //                  click={() => this.saveHandle(props.row, status)}>
            //   {statusName}
            // </multiuse-button>
            // <el-divider direction="vertical"/>
            // <multiuse-button type="text"
            //                  size="mini"
            //                  click={() => this.saveHandle(props.row, 0)}>
            //   保存
            // </multiuse-button>

            return (
              <div>
                <el-button size="mini" type="text" onClick={() => this.detailHandle(props.row)}>
                  详情
                </el-button>
              </div>
            );
          }
        },

        {
          title: '规则编号',
          dataIndex: 'threeNo',
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '规则名称',
          dataIndex: 'threeName',
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '状态',
          dataIndex: 'status',
          sorter: true,
          filter: true,
          filterType: 'checkbox',
          filterItems: this.createDictList(1004),
          render: props => {
            let status = props.row.status == '10041001' ? '已解锁' : '已锁定';
            return <span>{status}</span>;
          }
        },
        {
          title: '规则类型',
          dataIndex: 'type',
          sorter: true,
          filter: true,
          filterType: 'checkbox',
          filterItems: this.createDictList(1023),
          render: props => {
            return <span>{this.createDictText(props.row.type, 1023)}</span>;
          }
        },

        {
          title: '红色预警',
          dataIndex: 'red',
          sorter: true,
          filter: true,
          filterType: 'input',
          editable: false,
          editType: 'number',
          className: 'red'
          // render: props =>
          // {
          //   return <input style="color: red">{props.row.red}</input>;
          // }
        },
        {
          title: '橙色预警',
          dataIndex: 'orange',
          sorter: true,
          filter: true,
          filterType: 'input',
          editType: 'number',
          editable: false
          // render: props =>
          // {
          //   return <input style="color: orange">{props.row.orange}</input>;
          // }
        },
        {
          title: '黄色预警',
          dataIndex: 'yellow',
          width: 150,
          sorter: true,
          filter: true,
          filterType: 'input',
          editType: 'number',
          editable: false
          // render: props =>
          // {
          //   return <input style="color: yellow">{props.row.yellow}</input>;
          // }
        },
        {
          title: '创建人',
          dataIndex: 'createdBy',
          showOverflowTooltip: true,
          sorter: true,
          dictItems: []
        },
        {
          title: '创建时间',
          dataIndex: 'createdAt',
          width: 150,
          sorter: true,
          filter: true,
          filterType: 'date-range'
        },
        {
          title: '修改人',
          dataIndex: 'updatedBy',
          showOverflowTooltip: true,
          sorter: true,
          dictItems: []
        },
        {
          title: '修改时间',
          dataIndex: 'updatedAt',
          width: 150,
          sorter: true,
          filter: true,
          filterType: 'date-range'
        }
      ];
    },
    createTopFilterList() {
      return [
        {
          type: 'INPUT',
          label: '配件代码',
          fieldName: 'partNo',
          placeholder: '配件代码...'
        },
        {
          type: 'INPUT',
          label: '配件名称',
          fieldName: 'partName',
          placeholder: '配件名称...'
        },
        {
          type: 'SELECT',
          label: '规则类型',
          fieldName: 'type',
          placeholder: '规则类型',
          itemList: this.createDictList(1023)
        }
      ];
    },
    collapseHandle() {
      this.$nextTick(() => {
        this.BaseTable.EXECUTE_RESET_HEIGHT();
      });
    },

    changeHandle(val) {
      // val.bDate=moment(val['bDate']).format('YYYY-MM-DD')
      // val.eDate=moment(val['eDate']).format('YYYY-MM-DD')
      this.fetchParams = Object.assign({}, val);

      console.log(this.fetchParams);
    },
    showHandler() {
      this.dialogTitle = `${this.conf[this.handleType]}三包预警参数管理`;

      this.visibleDetail = true;
    },

    closeHandler(type) {
      this.visible = false;
      this.visibleDetail = false;
      if (type === 'refresh') {
        // 重新加载
        this.fetchParams = { ...this.fetchParams };
      }
    }
  }
};
</script>

<style lang="less" scoped>
.red {
  color: red !important;
}

.orange {
  color: orange;
}

.yellow {
  color: yellow;
}
</style>
